"""
配置预设管理 API 路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, joinedload
from typing import Optional

from database import get_db
from models.config_presets import ObsBucketPreset, ResourcePoolPreset, ImagePreset, NasPreset, Application
from schemas.config_preset_schema import (
    ObsBucketPresetCreate,
    ObsBucketPresetUpdate,
    ObsBucketPresetResponse,
    ObsBucketPresetListResponse,
    ResourcePoolPresetCreate,
    ResourcePoolPresetUpdate,
    ResourcePoolPresetResponse,
    ResourcePoolPresetListResponse,
    ImagePresetCreate,
    ImagePresetUpdate,
    ImagePresetResponse,
    ImagePresetListResponse,
    NasPresetCreate,
    NasPresetUpdate,
    NasPresetResponse,
    NasPresetListResponse,
)

router = APIRouter(prefix="/api/config-presets", tags=["配置预设管理"])


# ========== OBS桶配置预设 ==========
@router.post("/obs-buckets", response_model=ObsBucketPresetResponse, summary="创建OBS桶配置预设")
def create_obs_bucket_preset(
    preset_create: ObsBucketPresetCreate,
    db: Session = Depends(get_db)
):
    """创建OBS桶配置预设"""
    # 检查应用是否存在
    application = db.query(Application).filter(Application.id == preset_create.application_id).first()
    if not application:
        raise HTTPException(status_code=404, detail=f"应用ID '{preset_create.application_id}' 不存在")

    # 检查名称是否重复
    existing = db.query(ObsBucketPreset).filter(ObsBucketPreset.name == preset_create.name).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"预设名称 '{preset_create.name}' 已存在")

    preset = ObsBucketPreset(
        name=preset_create.name,
        bucket_id=preset_create.bucket_id,
        bucket_path=preset_create.bucket_path,
        description=preset_create.description,
        application_id=preset_create.application_id,
        created_by=preset_create.created_by,
    )
    db.add(preset)
    db.commit()
    db.refresh(preset)
    return preset


@router.get("/obs-buckets", response_model=ObsBucketPresetListResponse, summary="获取OBS桶配置预设列表")
def get_obs_bucket_presets(
    active_only: bool = True,
    application_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取OBS桶配置预设列表"""
    query = db.query(ObsBucketPreset).options(joinedload(ObsBucketPreset.application))
    if active_only:
        query = query.filter(ObsBucketPreset.is_active == True)
    if application_id is not None:
        query = query.filter(ObsBucketPreset.application_id == application_id)

    presets = query.order_by(ObsBucketPreset.created_at.desc()).all()
    return ObsBucketPresetListResponse(
        total=len(presets),
        items=presets
    )


@router.get("/obs-buckets/{preset_id}", response_model=ObsBucketPresetResponse, summary="获取OBS桶配置预设详情")
def get_obs_bucket_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """获取OBS桶配置预设详情"""
    preset = db.query(ObsBucketPreset).options(joinedload(ObsBucketPreset.application)).filter(ObsBucketPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")
    return preset


@router.put("/obs-buckets/{preset_id}", response_model=ObsBucketPresetResponse, summary="更新OBS桶配置预设")
def update_obs_bucket_preset(
    preset_id: int,
    preset_update: ObsBucketPresetUpdate,
    db: Session = Depends(get_db)
):
    """更新OBS桶配置预设"""
    preset = db.query(ObsBucketPreset).filter(ObsBucketPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    # 检查应用是否存在
    if preset_update.application_id is not None:
        application = db.query(Application).filter(Application.id == preset_update.application_id).first()
        if not application:
            raise HTTPException(status_code=404, detail=f"应用ID '{preset_update.application_id}' 不存在")

    # 检查名称是否重复（排除自己）
    if preset_update.name and preset_update.name != preset.name:
        existing = db.query(ObsBucketPreset).filter(
            ObsBucketPreset.name == preset_update.name,
            ObsBucketPreset.id != preset_id
        ).first()
        if existing:
            raise HTTPException(status_code=400, detail=f"预设名称 '{preset_update.name}' 已存在")

    # 更新字段
    if preset_update.name is not None:
        preset.name = preset_update.name
    if preset_update.bucket_id is not None:
        preset.bucket_id = preset_update.bucket_id
    if preset_update.bucket_path is not None:
        preset.bucket_path = preset_update.bucket_path
    if preset_update.description is not None:
        preset.description = preset_update.description
    if preset_update.application_id is not None:
        preset.application_id = preset_update.application_id
    if preset_update.is_active is not None:
        preset.is_active = preset_update.is_active

    db.commit()
    db.refresh(preset)
    return preset


@router.delete("/obs-buckets/{preset_id}", summary="删除OBS桶配置预设")
def delete_obs_bucket_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """删除OBS桶配置预设"""
    preset = db.query(ObsBucketPreset).filter(ObsBucketPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    db.delete(preset)
    db.commit()
    return {"message": "预设已删除"}


# ========== 资源池配置预设 ==========
@router.post("/resource-pools", response_model=ResourcePoolPresetResponse, summary="创建资源池配置预设")
def create_resource_pool_preset(
    preset_create: ResourcePoolPresetCreate,
    db: Session = Depends(get_db)
):
    """创建资源池配置预设"""
    # 检查应用是否存在
    application = db.query(Application).filter(Application.id == preset_create.application_id).first()
    if not application:
        raise HTTPException(status_code=404, detail=f"应用ID '{preset_create.application_id}' 不存在")

    # 检查名称是否重复
    existing = db.query(ResourcePoolPreset).filter(ResourcePoolPreset.name == preset_create.name).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"预设名称 '{preset_create.name}' 已存在")

    preset = ResourcePoolPreset(
        name=preset_create.name,
        pool_type=preset_create.pool_type,
        pool_uid=preset_create.pool_uid,
        spec_name=preset_create.spec_name,
        flavor_code=preset_create.flavor_code,
        description=preset_create.description,
        application_id=preset_create.application_id,
        created_by=preset_create.created_by,
    )
    db.add(preset)
    db.commit()
    db.refresh(preset)
    return preset


@router.get("/resource-pools", response_model=ResourcePoolPresetListResponse, summary="获取资源池配置预设列表")
def get_resource_pool_presets(
    active_only: bool = True,
    application_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取资源池配置预设列表"""
    query = db.query(ResourcePoolPreset).options(joinedload(ResourcePoolPreset.application))
    if active_only:
        query = query.filter(ResourcePoolPreset.is_active == True)
    if application_id is not None:
        query = query.filter(ResourcePoolPreset.application_id == application_id)

    presets = query.order_by(ResourcePoolPreset.created_at.desc()).all()
    return ResourcePoolPresetListResponse(
        total=len(presets),
        items=presets
    )


@router.get("/resource-pools/{preset_id}", response_model=ResourcePoolPresetResponse, summary="获取资源池配置预设详情")
def get_resource_pool_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """获取资源池配置预设详情"""
    preset = db.query(ResourcePoolPreset).options(joinedload(ResourcePoolPreset.application)).filter(ResourcePoolPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")
    return preset


@router.put("/resource-pools/{preset_id}", response_model=ResourcePoolPresetResponse, summary="更新资源池配置预设")
def update_resource_pool_preset(
    preset_id: int,
    preset_update: ResourcePoolPresetUpdate,
    db: Session = Depends(get_db)
):
    """更新资源池配置预设"""
    preset = db.query(ResourcePoolPreset).filter(ResourcePoolPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    # 检查应用是否存在
    if preset_update.application_id is not None:
        application = db.query(Application).filter(Application.id == preset_update.application_id).first()
        if not application:
            raise HTTPException(status_code=404, detail=f"应用ID '{preset_update.application_id}' 不存在")

    # 检查名称是否重复（排除自己）
    if preset_update.name and preset_update.name != preset.name:
        existing = db.query(ResourcePoolPreset).filter(
            ResourcePoolPreset.name == preset_update.name,
            ResourcePoolPreset.id != preset_id
        ).first()
        if existing:
            raise HTTPException(status_code=400, detail=f"预设名称 '{preset_update.name}' 已存在")

    # 更新字段
    if preset_update.name is not None:
        preset.name = preset_update.name
    if preset_update.pool_type is not None:
        preset.pool_type = preset_update.pool_type
    if preset_update.pool_uid is not None:
        preset.pool_uid = preset_update.pool_uid
    if preset_update.spec_name is not None:
        preset.spec_name = preset_update.spec_name
    if preset_update.flavor_code is not None:
        preset.flavor_code = preset_update.flavor_code
    if preset_update.description is not None:
        preset.description = preset_update.description
    if preset_update.application_id is not None:
        preset.application_id = preset_update.application_id
    if preset_update.is_active is not None:
        preset.is_active = preset_update.is_active

    db.commit()
    db.refresh(preset)
    return preset


@router.delete("/resource-pools/{preset_id}", summary="删除资源池配置预设")
def delete_resource_pool_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """删除资源池配置预设"""
    preset = db.query(ResourcePoolPreset).filter(ResourcePoolPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    db.delete(preset)
    db.commit()
    return {"message": "预设已删除"}


# ========== 镜像配置预设 ==========
@router.post("/images", response_model=ImagePresetResponse, summary="创建镜像配置预设")
def create_image_preset(
    preset_create: ImagePresetCreate,
    db: Session = Depends(get_db)
):
    """创建镜像配置预设"""
    # 检查应用是否存在
    application = db.query(Application).filter(Application.id == preset_create.application_id).first()
    if not application:
        raise HTTPException(status_code=404, detail=f"应用ID '{preset_create.application_id}' 不存在")

    # 检查名称是否重复
    existing = db.query(ImagePreset).filter(ImagePreset.name == preset_create.name).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"预设名称 '{preset_create.name}' 已存在")

    preset = ImagePreset(
        name=preset_create.name,
        image_uid=preset_create.image_uid,
        image_version=preset_create.image_version,
        image_version_uid=preset_create.image_version_uid,
        description=preset_create.description,
        application_id=preset_create.application_id,
        created_by=preset_create.created_by,
    )
    db.add(preset)
    db.commit()
    db.refresh(preset)
    return preset


@router.get("/images", response_model=ImagePresetListResponse, summary="获取镜像配置预设列表")
def get_image_presets(
    active_only: bool = True,
    application_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取镜像配置预设列表"""
    query = db.query(ImagePreset).options(joinedload(ImagePreset.application))
    if active_only:
        query = query.filter(ImagePreset.is_active == True)
    if application_id is not None:
        query = query.filter(ImagePreset.application_id == application_id)

    presets = query.order_by(ImagePreset.created_at.desc()).all()
    return ImagePresetListResponse(
        total=len(presets),
        items=presets
    )


@router.get("/images/{preset_id}", response_model=ImagePresetResponse, summary="获取镜像配置预设详情")
def get_image_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """获取镜像配置预设详情"""
    preset = db.query(ImagePreset).options(joinedload(ImagePreset.application)).filter(ImagePreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")
    return preset


@router.put("/images/{preset_id}", response_model=ImagePresetResponse, summary="更新镜像配置预设")
def update_image_preset(
    preset_id: int,
    preset_update: ImagePresetUpdate,
    db: Session = Depends(get_db)
):
    """更新镜像配置预设"""
    preset = db.query(ImagePreset).filter(ImagePreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    # 检查应用是否存在
    if preset_update.application_id is not None:
        application = db.query(Application).filter(Application.id == preset_update.application_id).first()
        if not application:
            raise HTTPException(status_code=404, detail=f"应用ID '{preset_update.application_id}' 不存在")

    # 检查名称是否重复（排除自己）
    if preset_update.name and preset_update.name != preset.name:
        existing = db.query(ImagePreset).filter(
            ImagePreset.name == preset_update.name,
            ImagePreset.id != preset_id
        ).first()
        if existing:
            raise HTTPException(status_code=400, detail=f"预设名称 '{preset_update.name}' 已存在")

    # 更新字段
    if preset_update.name is not None:
        preset.name = preset_update.name
    if preset_update.image_uid is not None:
        preset.image_uid = preset_update.image_uid
    if preset_update.image_version_uid is not None:
        preset.image_version_uid = preset_update.image_version_uid
    if preset_update.description is not None:
        preset.description = preset_update.description
    if preset_update.application_id is not None:
        preset.application_id = preset_update.application_id
    if preset_update.is_active is not None:
        preset.is_active = preset_update.is_active
    if preset_update.image_version is not None:
        preset.image_version = preset_update.image_version

    db.commit()
    db.refresh(preset)
    return preset


@router.delete("/images/{preset_id}", summary="删除镜像配置预设")
def delete_image_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """删除镜像配置预设"""
    preset = db.query(ImagePreset).filter(ImagePreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    db.delete(preset)
    db.commit()
    return {"message": "预设已删除"}


# ========== NAS配置预设 ==========
@router.post("/nas", response_model=NasPresetResponse, summary="创建NAS配置预设")
def create_nas_preset(
    preset_create: NasPresetCreate,
    db: Session = Depends(get_db)
):
    """创建NAS配置预设"""
    # 检查应用是否存在
    application = db.query(Application).filter(Application.id == preset_create.application_id).first()
    if not application:
        raise HTTPException(status_code=404, detail=f"应用ID '{preset_create.application_id}' 不存在")

    # 检查名称是否重复
    existing = db.query(NasPreset).filter(NasPreset.name == preset_create.name).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"预设名称 '{preset_create.name}' 已存在")

    preset = NasPreset(
        name=preset_create.name,
        nas_name=preset_create.nas_name,
        nas_type=preset_create.nas_type,
        nas_uid=preset_create.nas_uid,
        nas_instance_id=preset_create.nas_instance_id,
        nas_shar_addr=preset_create.nas_shar_addr,
        description=preset_create.description,
        application_id=preset_create.application_id,
        created_by=preset_create.created_by,
    )
    db.add(preset)
    db.commit()
    db.refresh(preset)
    return preset


@router.get("/nas", response_model=NasPresetListResponse, summary="获取NAS配置预设列表")
def get_nas_presets(
    active_only: bool = True,
    application_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取NAS配置预设列表"""
    query = db.query(NasPreset).options(joinedload(NasPreset.application))
    if active_only:
        query = query.filter(NasPreset.is_active == True)
    if application_id is not None:
        query = query.filter(NasPreset.application_id == application_id)

    presets = query.order_by(NasPreset.created_at.desc()).all()
    return NasPresetListResponse(
        total=len(presets),
        items=presets
    )


@router.get("/nas/{preset_id}", response_model=NasPresetResponse, summary="获取NAS配置预设详情")
def get_nas_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """获取NAS配置预设详情"""
    preset = db.query(NasPreset).options(joinedload(NasPreset.application)).filter(NasPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")
    return preset


@router.put("/nas/{preset_id}", response_model=NasPresetResponse, summary="更新NAS配置预设")
def update_nas_preset(
    preset_id: int,
    preset_update: NasPresetUpdate,
    db: Session = Depends(get_db)
):
    """更新NAS配置预设"""
    preset = db.query(NasPreset).filter(NasPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    # 检查应用是否存在
    if preset_update.application_id is not None:
        application = db.query(Application).filter(Application.id == preset_update.application_id).first()
        if not application:
            raise HTTPException(status_code=404, detail=f"应用ID '{preset_update.application_id}' 不存在")

    # 检查名称是否重复（排除自己）
    if preset_update.name and preset_update.name != preset.name:
        existing = db.query(NasPreset).filter(
            NasPreset.name == preset_update.name,
            NasPreset.id != preset_id
        ).first()
        if existing:
            raise HTTPException(status_code=400, detail=f"预设名称 '{preset_update.name}' 已存在")

    # 更新字段
    if preset_update.name is not None:
        preset.name = preset_update.name
    if preset_update.nas_name is not None:
        preset.nas_name = preset_update.nas_name
    if preset_update.nas_type is not None:
        preset.nas_type = preset_update.nas_type
    if preset_update.nas_uid is not None:
        preset.nas_uid = preset_update.nas_uid
    if preset_update.nas_instance_id is not None:
        preset.nas_instance_id = preset_update.nas_instance_id
    if preset_update.nas_shar_addr is not None:
        preset.nas_shar_addr = preset_update.nas_shar_addr
    if preset_update.description is not None:
        preset.description = preset_update.description
    if preset_update.application_id is not None:
        preset.application_id = preset_update.application_id
    if preset_update.is_active is not None:
        preset.is_active = preset_update.is_active

    db.commit()
    db.refresh(preset)
    return preset


@router.delete("/nas/{preset_id}", summary="删除NAS配置预设")
def delete_nas_preset(
    preset_id: int,
    db: Session = Depends(get_db)
):
    """删除NAS配置预设"""
    preset = db.query(NasPreset).filter(NasPreset.id == preset_id).first()
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")

    db.delete(preset)
    db.commit()
    return {"message": "预设已删除"}
